<?php
/**
 * The MIT License
 *
 * Copyright (c) <year> <copyright holders>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Damiano Ciarla
 * @package lib
 * @subpackage validator
 */
class BXDValidatorManager
{
	/**
	 * Lista delle regole da validare
	 *
	 * @var array
	 */
	private $_rules	= array();

	/**
	 * Lista degli errori trovati dalla validazione
	 *
	 * @var array
	 */
	private $_errors = array();

	public function __construct()
	{
		Bxd::includeLib()->validator();
	}

	/**
	 * Aggiunta di una nuova regola di validazione
	 *
	 * @param string $field Nome del campo
	 * @param string $value Codice di validazione
	 *
	 * @return BXDValidatorRule
	 */
	public function addField($field)
	{
		Bxd::getInstance()->lib('validator')->loadClass('Field');
		$this->_rules[$field] = new BXDValidatorField($field);

		return $this->_rules[$field];
	}

	/**
	 * Metodo che verifica tutti i campi aggiunti e restituisce il risultato del controllo
	 *
	 * @param array $data Array associativo chiave valore
	 *
	 * @return boolean
	 */
	public function validate($data = null)
	{
		$this->_errors = array();

		foreach($this->_rules as $rule)
		{
			if(($data !== null && is_array($data) && array_key_exists($rule->getField(), $data)) || $data === null)
			{
				if(isset($data[$rule->getField()]))
					$rule->value($data[$rule->getField()]);

				if(!$rule->isValid())
					$this->_errors[$rule->getField()] = $rule->getErrors();
			}
		}

		return ((count($this->_errors)) ? false : true);
	}

	/**
	 * Restituisce la lista degli errori per ogni campo settato
	 *
	 * @return array
	 */
	public function getErrors()
	{
		return $this->_errors;
	}
}
?>
